﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows8Accelerator.Core.Xaml;
using SimpleRssReader.DataSources;
using SimpleRssReader.Model;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml;
using Windows8Accelerator.Core.Xaml.Helpers;
using Windows8Accelerator.Core.Xaml.ViewModels;

namespace SimpleRssReader.ViewModel
{
    public class BlogViewModel : ViewModelBase
    {
        private Blog _Blog;
        public Blog Blog
        {
            get { return this._Blog; }
            set { this.SetProperty(ref this._Blog, value); }
        }

        public async Task LoadAsync(Blog blog)
        {
            Blog = blog;
            ListHelper.MergeLists(Posts, blog.Posts, (s) => s.Id);

            var cachedPosts = await DataSource.CachedInstance.RetrieveLatestPostsAsync(blog, 21);
            var posts = cachedPosts.Object;
            ListHelper.MergeLists(Posts, posts, (s) => s.Id);

            if (cachedPosts.CacheDate < DateTime.Now.AddHours(-1))
            {
                posts = await DataSource.Instance.RetrieveLatestPostsAsync(blog, 21);
                ListHelper.MergeLists(Posts, posts, (s) => s.Id);
            }
        }

        private ObservableCollection<Post> _Posts = new ObservableCollection<Post>();
        public ObservableCollection<Post> Posts
        {
            get { return this._Posts; }
        }
    }
}
